package com.chatcompetition.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
//图片上传接口
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    // 定义图片存储的目录
    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/image")
    public String uploadFile(MultipartFile file) {
        try {
            // 创建目录（如果不存在）
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

            // 保存文件到指定目录   以字节流的形式读取文件内容
            Path filePath = uploadPath.resolve(fileName);
            try (InputStream inputStream = file.getInputStream()) { // 使用 try-with-resources 自动关闭流
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            }
            log.info("文件上传成功: " + filePath.toString());
            log.info("文件上传成功: " + fileName);

            // 返回文件的相对路径
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }
}